<?php

namespace App\Http\Middleware;

use Closure;

/**
 * HTTP 基础认证中间件，使用时需传入用户名、密码：
 * middleware('auth.basic.validated:username,password')
 */
class ValidateBasicAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $username, $password)
    {
        if ($username && $password) {
            header('Cache-Control: no-cache, must-revalidate, max-age=0');
            $has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));
            $is_not_authenticated = (
                !$has_supplied_credentials ||
                $_SERVER['PHP_AUTH_USER'] != $username ||
                $_SERVER['PHP_AUTH_PW']   != $password
            );
            if ($is_not_authenticated) {
                header('HTTP/1.1 401 Authorization Required');
                header('WWW-Authenticate: Basic realm="Access denied"');
                exit;
            }
        }
        return $next($request);
    }
}
